﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VideoClassLibrary.Extension
{
    public static class StringExtension
    { /// <summary>
        /// 字符串为null或string.Empty时，则返回参数值

        /// </summary>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string ToEmptyOrDefaultValue(this string value, string defaultValue)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }
            else
                return defaultValue;
        }
        /// <summary>
        /// 将字符串格式化成HTML代码
        /// </summary>
        /// <param name="str">要格式化的字符串</param>
        /// <returns>格式化后的字符串</returns>
        public static string ToHtml(this string str)
        {
            if (str == null || str.Equals(""))
            {
                return str;
            }

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\r\n", "<br>");
            sb.Replace("\n", "<br>");
            sb.Replace("\t", " ");
            sb.Replace(" ", "&nbsp;");
            return sb.ToString();
        }



        /// <summary>
        /// 将HTML代码转化成文本格式
        /// </summary>
        /// <param name="str">要格式化的字符串</param>
        /// <returns>格式化后的字符串</returns>
        public static string  ToTxt(this string str)
        {
            if (str == null || str.Equals(""))
            {
                return str;
            }

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&nbsp;", " ");
            sb.Replace("<br>", "\r\n");
            sb.Replace("&lt;", "<");
            sb.Replace("&gt;", ">");
            sb.Replace("&amp;", "&");


            return sb.ToString();
        }

    }
}
